class BluetoothManager {
		constructor() {
				this.main = plus.android.runtimeMainActivity();
				this.IntentFilter = plus.android.importClass('android.content.IntentFilter');
				this.BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				this.BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
				this.BluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");
				this.UUID = plus.android.importClass("java.util.UUID");

				// 存储已发现的蓝牙设备信息
				this.discoveredDevices = new Map();
		}

		searchDevices() {
				return new Promise((resolve, reject) => {
						const BAdapter = this.BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter || !BAdapter.isEnabled()) {
								reject(new Error("蓝牙未开启或不支持"));
								return;
						}

						console.log("开始搜索设备");

						this._registerReceiver().then(() => {
								BAdapter.startDiscovery();
								resolve(this.discoveredDevices);
						}).catch(reject);
				});
		}

		stopSearching() {
				return new Promise((resolve, reject) => {
						const BAdapter = this.BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter || !BAdapter.isEnabled()) {
								reject(new Error("蓝牙未开启或不支持"));
								return;
						}

						BAdapter.cancelDiscovery();
						this._unregisterReceiver().then(resolve).catch(reject);
						console.log("搜索结束");
				});
		}

		connectToDevice(address, uuid) {
				return new Promise((resolve, reject) => {
						const BAdapter = this.BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter || !BAdapter.isEnabled()) {
								reject(new Error("蓝牙未开启或不支持"));
								return;
						}


						const device = BAdapter.getRemoteDevice(address);
						const socket = device.createRfcommSocketToServiceRecord(this.UUID.fromString(uuid));
						
						socket.connect();
						
						resolve(socket);
				});
		}

		sendData(socket, data) {
				return new Promise((resolve, reject) => {
						try{
							const outputStream = socket.getOutputStream();
							outputStream.write(data);
							outputStream.flush();
						}catch(e){
							//TODO handle the exception
							console.log(e)
						}
						resolve();
				});
		}

		receiveData(socket) {
				return new Promise((resolve, reject) => {
						const inputStream = socket.getInputStream();
						const buffer = new ArrayBuffer(1024);
						const bytes = new Uint8Array(buffer);

						let totalBytesRead = 0;
						let isEndOfStream = false;

						const readChunk = () => {
								inputStream.read(bytes, totalBytesRead, buffer.byteLength - totalBytesRead)
										.then((bytesRead) => {
												if (bytesRead < 0) {
														isEndOfStream = true;
														resolve(buffer.slice(0, totalBytesRead));
												} else {
														totalBytesRead += bytesRead;
														if (!isEndOfStream) {
																readChunk();
														}
												}
										})
										.catch(reject);
						};

						readChunk();
				});
		}

		_registerReceiver() {
				return new Promise((resolve, reject) => {
						
						const receiver = this._createReceiver();
						const filter = this._setIntentFilter();
						try {
								this.main.registerReceiver(receiver, filter);
								console.log('广播接收器已注册');
								resolve();
						} catch (e) {
								console.error('注册广播接收器失败: ', e);
								reject(new Error("注册广播接收器失败"));
						}
				});
		}

		_unregisterReceiver() {
				return new Promise((resolve, reject) => {
						const receiver = this._createReceiver();
						try {
								this.main.unregisterReceiver(receiver);
								resolve();
						} catch (e) {
								console.error("注销广播接收器失败: ", e);
								reject(new Error("注销广播接收器失败"));
						}
				});
		}

		_createReceiver() {
				const receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
						onReceive: function(context, intent) {
								plus.android.importClass(intent); // 通过intent实例引入intent类
								console.log(intent.getAction());

								if (intent.getAction() === "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
										console.log("搜索结束");
										console.log(JSON.stringify(this.discoveredDevices))
								} else {
										const BleDevice = intent.getParcelableExtra(this.BluetoothDevice.EXTRA_DEVICE);
										const isUnpaired = BleDevice.getBondState() === this.BluetoothDevice.BOND_NONE;
										const deviceInfo = { name: BleDevice.getName(), address: BleDevice.getAddress() };

										if (!this.discoveredDevices.has(deviceInfo.address)) {
												this.discoveredDevices.set(deviceInfo.address, deviceInfo);

												const infoMessage = `蓝牙设备：${deviceInfo.name}，地址：${deviceInfo.address}\n`;
												console.log(infoMessage);
												// updateInfo(infoMessage, isUnpaired); // 可在此处添加回调函数，将发现的新设备信息传递给调用者
										}
								}
						}.bind(this)
				});
				return receiver;
		}

		_setIntentFilter() {
				const filter = new this.IntentFilter();
				try{
					filter.addAction(this.BluetoothDevice.ACTION_FOUND);
					filter.addAction(this.BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
					filter.addAction(this.BluetoothAdapter.ACTION_STATE_CHANGED);
				}catch(e){
					//TODO handle the exception
					console.log(e)
				}
				
				return filter;
		}
	}

export default BluetoothManager



